package com.ruoyi.ysNewVideo.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.ysNewVideo.domain.NewGetVideoAutoTask;
import com.ruoyi.ysNewVideo.domain.NewPresetInfo;
import com.ruoyi.ysNewVideo.domain.NewVideoAutoTask;
import com.ruoyi.ysNewVideo.domain.NewVideoDao;
import com.ruoyi.ysNewVideo.service.NewVideoAutoTaskService;
import com.ruoyi.ysNewVideo.service.NewVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @program: class by cxf
 * @author: AbrahamBill
 * @date: 2022/8/12
 **/
@Api("视频定时任务处理类")
@Slf4j
@RestController
@RequestMapping("/NewVideoAutoTask")
public class NewVideoAutoTaskController {

    /**
     * 获取身份令牌
     */
    @Autowired
    private TokenService tokenService;

    /**
     * 获取萤石云 key
     */
    @Value("${ys7New.ys7AppKey}")
    private String ys7AppKey;

    /**
     * 获取萤石云密钥
     */
    @Value("${ys7New.ys7AppSecret}")
    private String ys7AppSecret;

    /**
     * 萤石云 Token Url
     */
    @Value("${ys7New.ys7tokenUrl}")
    private String ys7tokenUrl;

    /**
     * 萤石云 获取-播放地址 Url
     */
    @Value("${ys7New.ys7LiveAddress}")
    private String ys7LiveAddress;

    /**
     * 萤石云 抓拍图片地址
     */
    @Value("${ys7New.ys7CaptureUrl}")
    private String ys7CaptureUrl;

    /**
     * 萤石云 添加预置位
     */
    @Value("${ysOperation.ys7PresetAdd}")
    private String ys7PresetAdd;

    /**
     * 萤石云 调用预置位
     */
    @Value("${ysOperation.ys7PresetMove}")
    private String ys7PresetMove;


    /**
     * 萤石云 清除预置位
     */
    @Value("${ysOperation.ys7PresetClear}")
    private String ys7PresetClear;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * service
     */
    @Autowired
    private NewVideoService newVideoService;

    /**
     * service
     */
    @Autowired
    private NewVideoAutoTaskService newVideoAutoTaskService;

    @ApiOperation("查看所有定时任务")
    @GetMapping("/selectAllTask")
    public AjaxResult selectAllTask(){
        return AjaxResult.success(newVideoAutoTaskService.selectAllTask());
    }

    @ApiOperation("根据设备序列号查看所有定时任务")
    @GetMapping("/selectAllTaskBydeviceSerial")
    public AjaxResult selectAllTaskBydeviceSerial(NewVideoAutoTask videoAutoTask){
        return AjaxResult.success(newVideoAutoTaskService.selectAllTaskBydeviceSerial(videoAutoTask));
    }

    @ApiOperation("开始自动任务")
    @PostMapping("/startTask")
    public AjaxResult startTask(NewGetVideoAutoTask newGetVideoAutoTask) {
        String cron="";
        NewVideoAutoTask newVideoAutoTask = new NewVideoAutoTask();
        if(newGetVideoAutoTask.getIsEachHour()==1){
            cron=newGetVideoAutoTask.getSecond().toString()+" "+newGetVideoAutoTask.getMinute().toString()+"  * * * ?";
        }else {
            cron=newGetVideoAutoTask.getSecond().toString()+" "+newGetVideoAutoTask.getMinute().toString()+" "+newGetVideoAutoTask.getHour().toString()+ " * * ?";
        }
        if(newGetVideoAutoTask.getIsNowPreset()==1){
            NewPresetInfo newPresetInfo = new NewPresetInfo();
            newPresetInfo.setDeviceSerial(newGetVideoAutoTask.getDeviceSerial());
            newPresetInfo.setRemark(newGetVideoAutoTask.getRemark());
            NewVideoDao NewVideoDao = newVideoService.selectVideoLast();
            log.info("---------->" + NewVideoDao.toString());
//        String getLiveAddressUrl = ys7LiveAddress + "?accessToken=" + videoDao.getAccessToken() + "&deviceSerial=" + videoDao.getDeviceSerial();
            String getLiveAddressUrl = ys7PresetAdd + "?accessToken=" + NewVideoDao.getAccessToken() + "&deviceSerial=" + newPresetInfo.getDeviceSerial()+"&channelNo=1";
            log.info(getLiveAddressUrl);
            try {
                ResponseEntity<String> responseEntity = Threads.postRequest(getLiveAddressUrl);
                /* 拿到data数据 */
                JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
                String code=jsonObject.get("code").toString();
                if(code.equals("60008")){
                    return AjaxResult.error("添加的预置点个数达到上限（300个），请清除不需要的预置点后在进行添加操作");
                }else if(code.equals("200")) {
                    Integer nowIndex = Integer.valueOf(jsonObject.getJSONObject("data").get("index").toString());
                    log.info(String.valueOf(nowIndex));
                    newPresetInfo.setIndexId(nowIndex);
                    newVideoService.insertPreset(newPresetInfo);

                    newVideoAutoTask.setPresetIndexId(nowIndex);
                    newVideoAutoTask.setDeviceSerial(newGetVideoAutoTask.getDeviceSerial());
                    newVideoAutoTask.setCron(cron);
                    int id = newVideoAutoTaskService.insertAutoTask(newVideoAutoTask);
                    return AjaxResult.success(id);
                }else {
                    return AjaxResult.error("未知错误，请联系管理员，错误码："+code);
                }
            } catch (Exception e) {
                System.out.println(e);
                return AjaxResult.error("添加预置位出错！请重试!");
            }
        }else {
            newVideoAutoTask.setPresetIndexId(newGetVideoAutoTask.getIndexId());
            newVideoAutoTask.setDeviceSerial(newGetVideoAutoTask.getDeviceSerial());
            newVideoAutoTask.setCron(cron);
            int id = newVideoAutoTaskService.insertAutoTask(newVideoAutoTask);
            return AjaxResult.success(id);
        }


    }

    /**
     * 根据id关闭任务
     **/
    @GetMapping("/stopTask")
    public AjaxResult stopCron(Integer id) {

        newVideoAutoTaskService.deleteAutoTask(id);
        return AjaxResult.success(id);
    }

    /**
     * 修改自动任务
     **/
    @PostMapping("/changeTask")
    public AjaxResult changeTask(NewGetVideoAutoTask newGetVideoAutoTask) {
        newVideoAutoTaskService.deleteAutoTask(newGetVideoAutoTask.getId());
        String cron="";
        NewVideoAutoTask newVideoAutoTask = new NewVideoAutoTask();
        if(newGetVideoAutoTask.getIsEachHour()==1){
            cron=newGetVideoAutoTask.getSecond().toString()+" "+newGetVideoAutoTask.getMinute().toString()+"  * * * ?";
        }else {
            cron=newGetVideoAutoTask.getSecond().toString()+" "+newGetVideoAutoTask.getMinute().toString()+" "+newGetVideoAutoTask.getHour().toString()+ " * * ?";
        }
        newVideoAutoTask.setPresetIndexId(newGetVideoAutoTask.getIndexId());
        newVideoAutoTask.setDeviceSerial(newGetVideoAutoTask.getDeviceSerial());
        newVideoAutoTask.setCron(cron);
        int id = newVideoAutoTaskService.insertAutoTask(newVideoAutoTask);
        return AjaxResult.success(id);
    }

    @ApiOperation("测试")
    @PostMapping("/test")
    public AjaxResult test(@RequestParam("imageName") MultipartFile file) throws IOException {
        System.out.println(new Date());
        /**
         * 上传图片
         */
        //图片上传成功后，将图片的地址写到数据库
        //保存图片的路径（这是存在我项目中的images下了，你们可以设置路径）
        String filePath = "G:\\tmp";
        //获取原始图片的拓展名
        String originalFilename = file.getOriginalFilename();
        //新的文件名字
        String newFileName = UUID.randomUUID() + originalFilename;
        //封装上传文件位置的全路径
        File targetFile = new File(filePath, newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        file.transferTo(targetFile);


        return AjaxResult.success("成功");
    }
}
